package com.yxw.yxnet_cd_center.customer_service.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yxw.yxnet_cd_center.common.dto.PageVO;
import com.yxw.yxnet_cd_center.common.exception.BaseException;
import com.yxw.yxnet_cd_center.customer_service.dto.DataGroupDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.DataGroupQueryDTO;
import com.yxw.yxnet_cd_center.customer_service.dto.DataGroupTagDTO;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsCustTagEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsDataGroupEntity;
import com.yxw.yxnet_cd_center.customer_service.entity.YxCsTagEntity;
import com.yxw.yxnet_cd_center.customer_service.mapper.CustMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.DataGroupMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.RelevancyMapper;
import com.yxw.yxnet_cd_center.customer_service.mapper.TagMapper;
import com.yxw.yxnet_cd_center.customer_service.service.IDataGroupService;
import com.yxw.yxnet_cd_center.customer_service.utils.PageUtils;
import com.yxw.yxnet_cd_center.customer_service.vo.DataGroupVO;
import com.yxw.yxnet_cd_center.customer_service.vo.TagVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * 大数据分组Service业务层处理
 *
 * @author xiexuxin
 * @date 2023-09-25
 */
@Slf4j
@Service
public class DataGroupServiceImpl extends ServiceImpl<DataGroupMapper, YxCsDataGroupEntity> implements IDataGroupService {

    @Autowired
    private DataGroupMapper dataGroupMapper;

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private RelevancyMapper relevancyMapper;

    @Autowired
    private CustMapper custMapper;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTag(DataGroupTagDTO tagDTO) {
        log.info("开始处理添加标签的业务，参数：{}", tagDTO);
        YxCsTagEntity tag = new YxCsTagEntity();
        BeanUtils.copyProperties(tagDTO, tag);
        tag.setCreateTime(LocalDateTime.now());
        int rows = tagMapper.insert(tag);
        if (rows != 1) {
            throw new BaseException("添加标签失败，服务器忙，请稍后再尝试！");
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addDataGroup(DataGroupDTO dataGroupDTO) {
        log.info("开始处理添加客户数据的业务，参数：{}", dataGroupDTO);
        YxCsDataGroupEntity dataGroup = new YxCsDataGroupEntity();
        BeanUtils.copyProperties(dataGroupDTO, dataGroup);
        dataGroup.setCustId(dataGroupDTO.getCustId());
        dataGroup.setCreateTime(LocalDateTime.now());
        LambdaQueryWrapper<YxCsDataGroupEntity> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(true, YxCsDataGroupEntity::getCustName, dataGroupDTO.getCustName())
                .eq(true, YxCsDataGroupEntity::getChannelCode, dataGroupDTO.getChannelCode());
        YxCsDataGroupEntity existingDataGroup = dataGroupMapper.selectOne(queryWrapper);
        if (existingDataGroup != null) {
            Long existingDataId = existingDataGroup.getCustId();
            LocalDateTime createTime = existingDataGroup.getCreateTime();
            String channelName = existingDataGroup.getChannelName();
            relevancyMapper.deleteCustTagBycustId(existingDataId);
            dataGroupMapper.deleteById(existingDataGroup.getDataId());
            dataGroup.setUpdateTime(LocalDateTime.now());
            dataGroup.setCreateTime(createTime);
            dataGroup.setChannelName(channelName);
        }
        int rows = dataGroupMapper.insert(dataGroup);
        if (rows != 1) {
            throw new BaseException("添加客户数据失败，服务器忙，请稍后再尝试！");
        }
        Long[] tagIds = dataGroupDTO.getLabelTypes();
        Set<Long> set = new HashSet<>();
        for (Long tagId : tagIds) {
            if (!set.add(tagId)) {
                throw new BaseException("请勿添加重复的标签");
            }
        }
        if (tagIds != null && tagIds.length > 0) {
            List<YxCsCustTagEntity> custTagList = new ArrayList<>();
            YxCsCustTagEntity custTagEntity = new YxCsCustTagEntity();
            custTagEntity.setCustId(dataGroupDTO.getCustId());
            custTagEntity.setLabelTypes(tagIds);
            custTagList.add(custTagEntity);
            if (custTagList.stream().anyMatch(custTag -> custTag.getLabelTypes() == null || custTag.getLabelTypes().length == 0)) {
                return;
            }
            relevancyMapper.insertCustTags(custTagList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTag(Long id) {
        log.info("开始处理删除标签的业务，参数：{}", id);
        YxCsTagEntity tag = tagMapper.selectById(id);
        if (tag == null || tag.getTagId() == 0) {
            throw new BaseException("删除标签失败，尝试删除的标签数据不存在！");
        }
        relevancyMapper.deleteCustTagByTagId(id);
        int rows = tagMapper.deleteById(id);
        if (rows != 1) {
            throw new BaseException("删除标签失败，服务器忙，请稍后再试！");
        }
    }

    @Override
    public List<TagVO> tagList() {
        LambdaQueryWrapper<YxCsTagEntity> queryWrapper = new LambdaQueryWrapper<>();
        List<YxCsTagEntity> entityList = tagMapper.selectList(queryWrapper);
        List<TagVO> voList = new ArrayList<>();
        if(null!=entityList && !entityList.isEmpty()){
            voList = BeanUtil.copyToList(entityList, TagVO.class);
        }
       return voList;
    }

    @Override
    public PageVO<DataGroupVO> getDataGroupList(DataGroupQueryDTO dataGroupQueryDTO) {
        log.info("开始处理【条件查询大数据分组列表】的业务，条件参数：{}", dataGroupQueryDTO);
        Page<DataGroupVO> page = new Page<>(dataGroupQueryDTO.getCurrPage(), dataGroupQueryDTO.getPageSize());
        List<DataGroupVO> list = dataGroupMapper.getDataGroupByCondition(page, dataGroupQueryDTO);
        for (DataGroupVO dataGroup : list) {
            Long dataId = dataGroup.getDataId();
            String channelName = dataGroup.getChannelName();
            updateChannel(dataId, channelName);
        }
        return PageUtils.get(page,list);
    }

    @Override
    public PageVO<DataGroupVO> getDataGroupByTag(Long tagId) {
        log.info("开始处理【根据标签id查询对应客户】的业务，条件参数：{}", tagId);
        DataGroupQueryDTO dataGroupQueryDTO = new DataGroupQueryDTO();
        Page<DataGroupVO> page = new Page<>(dataGroupQueryDTO.getCurrPage(), dataGroupQueryDTO.getPageSize());
        List<DataGroupVO> list = dataGroupMapper.getDataGroupByTag(page, tagId);
        return PageUtils.get(page,list);
    }

    @Override
    public List<DataGroupVO> dataGroupList() {
        log.info("开始处理【查询大数据分组列表】的业务，无参数");
        return dataGroupMapper.dateGroupList();
    }

    @Transactional(rollbackFor = Exception.class)
    public void updateChannel(Long dataId, String channelName) {
        YxCsDataGroupEntity dataGroup = dataGroupMapper.selectById(dataId);
        dataGroup.setChannelName(channelName);
        dataGroupMapper.updateById(dataGroup);
    }
}
